//
//  WARedisterViewController.m
//  WalkiOS
//
//  Created by luqiuan on 2019/10/30.
//  Copyright © 2019 Chenmuzhou. All rights reserved.
//

#import "WARedisterViewController.h"

@interface WARedisterViewController ()
@property (weak, nonatomic) IBOutlet UILabel *titleLB;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *codeTF;
@property (weak, nonatomic) IBOutlet UITextField *passTF;//
@property (weak, nonatomic) IBOutlet UITextField *inviteTF;//可能是确认密码TF
@property (weak, nonatomic) IBOutlet UIImageView *invitaImageView;
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *ensureBtn;

@property (strong, nonatomic) NSString *codeString;
@property (strong, nonatomic) NSString *phoneNum;
@property (strong, nonatomic) NSTimer *codeTimer;
@property (assign, nonatomic) NSInteger timeCount;


@property (assign, nonatomic) NSInteger type;//0:注册页面  1：修改密码页面 2：修改支付页面  3:忘记密码页面
@end

@implementation WARedisterViewController

- (instancetype)initWithType:(NSInteger)type
{
    self = [super init];
    if (self) {
        self.type = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [self updateViews];
    self.passTF.secureTextEntry = YES;
}

- (void)updateViews{
    self.inviteTF.secureTextEntry = NO;
    if (self.type == 1) {
        self.titleLB.text = @"修改登录密码";
        self.phoneTF.userInteractionEnabled = NO;
        self.phoneTF.text = [self.loginManager.userInfo.phone phone];
        self.inviteTF.placeholder = @"确认密码";
        self.invitaImageView.image = [UIImage imageNamed:@"suo"];
        self.inviteTF.secureTextEntry = YES;
    }else if (self.type == 2) {
        self.titleLB.text = @"修改支付密码";
        self.phoneTF.userInteractionEnabled = NO;
        self.phoneTF.text = [self.loginManager.userInfo.phone phone];
        self.inviteTF.placeholder = @"确认密码";
        self.invitaImageView.image = [UIImage imageNamed:@"suo"];
        self.inviteTF.secureTextEntry = YES;
    }else if (self.type == 3) {
        self.titleLB.text = @"找回密码";
        self.phoneTF.userInteractionEnabled = YES;
        self.inviteTF.placeholder = @"确认密码";
        self.invitaImageView.image = [UIImage imageNamed:@"suo"];
        self.inviteTF.secureTextEntry = YES;
        [self.ensureBtn setTitle:@"提交" forState:0];
    }
 }

- (void)startTimer{
    self.getCodeBtn.userInteractionEnabled = NO;
    [self.getCodeBtn setTitle:[NSString stringWithFormat:@"重发(%dS)",120] forState:0];
    self.timeCount = 0;
    self.codeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
}

- (void)stopTimer{
    self.getCodeBtn.userInteractionEnabled = YES;
    [self.codeTimer invalidate];
    self.codeTimer = nil;
    [self.getCodeBtn setTitle:@"获取验证码" forState:0];
}

- (void)timeAction{
    self.timeCount ++;
    if (self.timeCount >= 120) {
        [self stopTimer];
        return;
    }
    [self.getCodeBtn setTitle:[NSString stringWithFormat:@"重发(%zdS)",120 - self.timeCount] forState:0];
}

- (void)requestCode{
    if (self.type == 0 || self.type == 3) {
        self.phoneNum = self.phoneTF.text;
    }else{
        self.phoneNum = self.loginManager.userInfo.phone;
    }
    if(![Utils isValidTelePhone:self.phoneNum]){
        [WNTool show:@"手机号错误"];
        return;
    }
    [WNTool showLoading];
    
    [WNBusinessRequest sendCodeWithPhone:self.phoneNum Succ:^(id  _Nonnull responseObject) {
        self.codeString = (NSString *)responseObject;
        [WNTool hideLoading];
        [WNTool show:@"获取成功"];
        [self startTimer];
    } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
        [WNTool show:mes];
    }];
}

- (void)registerRequest{
    
    if (![self.codeString isEqualToString:self.codeTF.text] || !(self.codeString.length == 6)) {
        [WNTool show:@"验证码错误"];
        return;
    }
    
    if(self.passTF.text.length < 6){
        [WNTool show:@"密码长度不能小于6位额"];
        return;
    }
    
    if (self.type == 1) {
        if(![self.passTF.text isEqualToString:self.inviteTF.text]){
            [WNTool show:@"两次输入的密码不一致"];
            return;
        }
    }
    
    [WNTool showLoading];
    if (self.type == 0) {
        [WNBusinessRequest registerWithPhone:self.phoneNum pass:self.passTF.text suserid:self.inviteTF.text Succ:^(id  _Nonnull responseObject) {
            [WNTool show:@"注册成功"];
            [self stopTimer];
            [self backAction:nil];
        } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
            [WNTool show:mes];
            [self stopTimer];
        }];
    }else if(self.type == 1){
        [WNBusinessRequest updateLoginpassWithPass:self.passTF.text Succ:^(id  _Nonnull responseObject) {
            [WNTool show:@"修改密码成功"];
            [self stopTimer];
            [self backAction:nil];
            [self.loginManager updateUserInfo:nil];
        } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
            [WNTool show:mes];
            [self stopTimer];
        }];
    }else if(self.type == 2){
        [WNBusinessRequest updatePaypassWithPass:self.passTF.text Succ:^(id  _Nonnull responseObject) {
            [WNTool show:@"修改密码成功"];
            [self stopTimer];
            [self backAction:nil];
            [self.loginManager updateUserInfo:nil];
        } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
            [WNTool show:mes];
            [self stopTimer];
        }];
    }else if(self.type == 3){
        [WNBusinessRequest modifyLoginpassWithPass:self.passTF.text phone:self.phoneNum Succ:^(id  _Nonnull responseObject) {
            [WNTool show:@"修改成功"];
            [self stopTimer];
            [self backAction:nil];
        } fail:^(NSString * _Nonnull code, NSString * _Nonnull mes) {
            [WNTool show:mes];
            [self stopTimer];
        }];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self returnWithTF:textField];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.tag == 0) {
        return YES;
    }else{
        if (textField.text.length > 18 && ![string isEqualToString:@""]) {
            return NO;
        }
        return YES;
    }
}

- (void)returnWithTF:(UITextField *)textField{
    switch (textField.tag) {
        case 0://手机号
            {
                NSLog(@"--ID:%@",textField.text);
            }
            break;
        case 1://验证码
            {
                NSLog(@"--NickName:%@",textField.text);
            }
            break;
        case 2://密码
            {
                NSLog(@"--Sex:%@",textField.text);
            }
            break;
        case 3://邀请码
            {
                NSLog(@"--Wechat:%@",textField.text);
            }
            break;
        default:
            break;
    }
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)getCodeAction:(id)sender {
    [self requestCode];
}

- (IBAction)registerAction:(id)sender {
    [self registerRequest];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    CGRect keyBoardframe = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat spaceH = 40;
        // 强迫症，不能忍警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wundeclared-selector"
    UITextField *tf = [self.view.window performSelector:@selector(firstResponder)];
#pragma clang diagnostic pop
    CGRect rect1 = [self.view  convertRect:tf.frame fromView:tf.superview];
    CGFloat margin = keyBoardframe.size.height + spaceH - (WNScreenHeight - CGRectGetMaxY(rect1));
    if (margin <= 0) {
        return;
    }
    [UIView animateWithDuration:0.2 animations:^{
        self.scrollView.transform = CGAffineTransformMakeTranslation(0, - margin);
    } completion:^(BOOL finished) {
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView animateWithDuration:0.2 animations:^{
        self.scrollView.transform = CGAffineTransformIdentity;
    }];
}
@end
